#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/1/23 11:35
# @Author  : Wang Feng
# @FileName: testscript.py
# @Software: PyCharm
import uuid

import jenkins
from flask import Blueprint, request, jsonify
from flask_restful import inputs

from app.models import TestScript, TestTask
from app.settings import JENKINS_URI, JENKINS_USERNAME, JENKINS_PASSWORD
from app.utils.response_code import RET

testscript = Blueprint('testscript', __name__)


@testscript.route('/list', methods=['POST'])
def list_testscript():
    epic = request.form.get('epic', type=str)
    feature = request.form.get('feature', type=str)
    story = request.form.get('story', type=str)
    title = request.form.get('title', type=str)
    test_case_id = request.form.get('test_case_id', type=str)
    has_test_case = request.form.get('has_test_case', type=inputs.boolean)
    marks = request.form.get('marks', type=str)
    author = request.form.get('author', type=str)
    page_num = request.form.get('page_num', 1, type=int)
    page_size = request.form.get('page_size', 10, type=int)

    filter_list = []
    if epic:
        filter_list.append(TestScript.epic.contains(epic))
    if feature:
        filter_list.append(TestScript.feature.contains(feature))
    if story:
        filter_list.append(TestScript.story.contains(story))
    if title:
        filter_list.append(TestScript.title.contains(title))
    if test_case_id:
        filter_list.append(TestScript.test_case_id.contains(test_case_id))
    if has_test_case in (True, False):
        filter_list.append(TestScript.has_test_case == has_test_case)
    if marks:
        filter_list.append(TestScript.marks.contains(marks))
    if author:
        filter_list.append(TestScript.author.contains(author))
    pagination = TestScript.query.filter(*filter_list).order_by(TestScript.id).paginate(page=page_num,
                                                                                        per_page=page_size)
    total_page = pagination.pages
    count = pagination.total
    test_scripts = pagination.items
    data = list(map(lambda test_script: test_script.to_dict(), test_scripts))
    return jsonify(code=RET.OK, msg='查询成功', total_page=total_page, count=count, data=data)


@testscript.route('/get_detail_by_id', methods=['GET'])
def get_detail_by_id():
    id = request.args.get('id')
    if id:
        testscript = TestScript.query.get(id)
        if testscript:
            return jsonify(code=RET.OK, msg='查询成功', data=testscript.to_dict())
        return jsonify(code=RET.NODATA, msg='数据不存在')
    return jsonify(code=RET.PARAMERR, msg='参数错误: id不能为空')


@testscript.route('/execute', methods=['POST'])
def execute():
    testscripts = request.form.get('testscripts')
    task_name = request.form.get('task_name')
    if not all([testscripts, task_name]):
        return jsonify(code=RET.PARAMERR, msg='参数不完整')
    server = jenkins.Jenkins(JENKINS_URI, username=JENKINS_USERNAME, password=JENKINS_PASSWORD)
    tests = str()
    print()
    test_full_name = testscripts.split(',')
    for test in test_full_name:
        tests += format_test_case(test) + ' '
    uid = str(uuid.uuid4())
    suid = ''.join(uid.split('-'))
    try:
        print(tests)
        queue_id = server.build_job('public_test', {'task_name': task_name, 'task_id': suid, 'test_cases': tests})
    except Exception as e:
        print(e)
        return jsonify(code=RET.SERVERERR, msg='执行失败')
    else:
        if queue_id is not None:
            testtask = TestTask()
            testtask.task_name = task_name
            testtask.task_id = suid
            testtask.result = 'pending'
            testtask.save()
            return jsonify(code=RET.OK, msg='执行成功')


def format_test_case(test_full_name):
    return '/'.join(test_full_name.split('.')[:-1]) + '.py'

